﻿using AutoMapper;
using B.S.DataBase.Domain;
using B.S.DataBase.ErrorCode;
using B.S.DataBase.Infrastructure;
using B.S.DataBase.Read.API.Application.Commands.GetProduct;
using B.S.DataBase.Read.API.Dtos;
using MediatR;
using System.Security;

namespace B.S.DataBase.Read.API.Application.Handlers.GetProduct
{
    public class GetProductHandler : IRequestHandler<GetProductCommand, PageResult<ProductDto>>
    {
        private readonly IBaseRepository<Product> productRepository;
        private readonly IBaseRepository<ProductType> typeRepository;
        private readonly IMapper mapper;

        public GetProductHandler(IBaseRepository<Product> productRepository, IBaseRepository<ProductType> typeRepository, IMapper mapper)
        {
            this.productRepository = productRepository;
            this.typeRepository = typeRepository;
            this.mapper = mapper;
        }

        public Task<PageResult<ProductDto>> Handle(GetProductCommand request, CancellationToken cancellationToken)
        {
            PageResult<ProductDto> result = new PageResult<ProductDto>();

            var linq = from a in productRepository.GetAllAsync().Where(x=>x.IsDeleted==false)
                       join b in typeRepository.GetAllAsync() on a.Id equals b.Id
                       select new ProductDto
                       {
                           Id = a.Id,
                           BatchId = a.BatchId,
                           KeepSafe = a.KeepSafe,
                           Permission = a.Permission,
                           FirmName = a.FirmName,
                           Full = a.Full,
                           ProductName = b.ProductName,
                       };

            result.TotalCount = linq.Count();
            result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            var page = linq.OrderBy(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            result.Code = APIEnums.Success;
            result.Meg = "查询成功";
            result.Data = mapper.Map<List<ProductDto>>(page);

            return Task.FromResult(result);
        }
    }
}
